<?php

/**
 * Class YJsTreeWidget
 *
 * @author Hua Yang <htmlcook@gmail.com>
 */
class YJsTreeWidget extends CWidget
{
	private static $_assets;
	public $htmlOptions = array();
	public $items = array();
	public $options = array();
	public $linkHtmlOptions = array();
	public $itemHtmlOptions = array();

	public $selected;

	private $_jsEnabled = true;

	public function init()
	{
		if ($this->options === array()) {
			$this->_jsEnabled = false;
		}
		if (!isset(self::$_assets) && $this->_jsEnabled) {
			/** @var CAssetManager $assetManager */
			$assetManager = Yii::app()->getAssetManager();
			self::$_assets = $assetManager->publish(dirname(__FILE__) . '/../assets/jstree');
			/** @var CClientScript $cs */
			$cs = Yii::app()->getClientScript();
			$cs->registerScriptFile(self::$_assets . '/jstree.min.js')
				->registerCssFile(self::$_assets . '/themes/default/style.min.css');
		}
	}

	public function run()
	{
		if (!isset($this->htmlOptions['id'])) {
			$id = $this->htmlOptions['id'] = $this->id;
		} else {
			$id = $this->htmlOptions['id'];
		}

		if (!isset($this->htmlOptions['class'])) {
			$this->htmlOptions['class'] = 'tree';
		} else {
			$this->htmlOptions['class'] = 'tree ' . $this->htmlOptions['class'];
		}

		echo CHtml::openTag('div', $this->htmlOptions);
		$this->renderItems($this->items);
		echo CHtml::closeTag('div');

		if ($this->options) {
			$options = CJavaScript::encode($this->options);
			Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $this->id, '$("#' . $id . '").jstree(' . $options . ');');
		}
	}

	public function renderItems($items)
	{
		static $depth = 1;
		echo CHtml::openTag('ul', array('class' => 'tree-depth-' . $depth++));
		foreach ($items as $item) {
			$itemHtmlOptions = array_merge($this->itemHtmlOptions,
				isset($item['itemHtmlOptions']) ? $item['itemHtmlOptions'] : array()
			);

			$linkHtmlOptions = array_merge($this->linkHtmlOptions,
				isset($item['linkHtmlOptions']) ? $item['linkHtmlOptions'] : array()
			);

			if ($item['id'] == $this->selected) {
				$item['jstree']['selected'] = true;
				if (isset($itemHtmlOptions['class'])) {
					$itemHtmlOptions['class'] = 'selected ' . $itemHtmlOptions['class'];
				} else {
					$itemHtmlOptions['class'] = 'selected';
				}
			}

			if (isset($item['jstree'])) {
				if ($this->_jsEnabled) {
					$itemHtmlOptions['data-jstree'] = json_encode($item['jstree']);
				} elseif (isset($item['jstree']['icon'])) {
					$item['label'] = '<span class="' . $item['jstree']['icon'] . '"></span> ' . $item['label'];
				}
			}

			if (!isset($item['url'])) {
				$item['url'] = '#';
			}

			echo CHtml::openTag('li', $itemHtmlOptions);
			echo CHtml::link($item['label'], $item['url'], $linkHtmlOptions);
			if (isset($item['items'])) {
				$this->renderItems($item['items']);
			}
			echo CHtml::closeTag('li');
		}
		echo CHtml::closeTag('ul');
	}
} 